<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t('上传升级文件')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="550px" top="5%" @close='close' class="licenceDialog">
    <div class="recoveryDialogContent">
      <el-upload class="upload-Upgrade" ref="upload" drag :action="global + '/backup/upload'" :on-success="handleAvatar" :on-error='handleAvatar' :before-upload="beforeAvatarUpload" accept='.pkg' :on-change="handleChange" :headers='headerConfig' :multiple='false' :file-list="fileList" :on-remove='removeFile'>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">{{$t('将文件拖到此处，或')}}<em>{{$t('点击上传')}}</em></div>
        <div class="el-upload__tip" slot="tip">{{$t('只能上传 PKG 文件')}}</div>
      </el-upload>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import global from '@/global'
import { getSessionId } from '@/utils/auth'
import { recoveryBackup } from '@/api/system/configManager'
export default {
  name: 'RecoveryDialog',
  data () {
    return {
      dialogVisible: false,
      fileList: [],
      headerConfig: {
        'session_id': getSessionId()
      },
      fileName: null,
      global: global.BASE_URL
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
    },
    submit () {
      if (this.fileName) {
        recoveryBackup({ name: this.fileName }).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('更新成功'))
            this.$parent.listData()
            this.close()
          }
        })
      } else {
        this.$messages.error(this.$t('请选择文件上传'))
      }
    },
    handleAvatar (res, file) {
      if (res.status === 0) {
        this.fileName = res.dir
      } else {
        this.$messages.error(res.msg || '上传失败')
      }
    },
    handleChange (file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    removeFile () {
      this.fileName = null
    },
    beforeAvatarUpload (file) {
      const isPKG = file.name.indexOf('.pkg') >= 0
      // const isLt1M = file.size / 1024 / 1024 < 1

      if (!isPKG) {
        this.$messages.error(this.$t('上传的文件只能是 PKG 格式!'))
      }
      // if (!isLt1M) {
      //   this.$messages.error(this.$t('上传的文件大小不能超过 1MB!'))
      // }
      // return isPKG && isLt1M
      return isPKG
    },
    close () {
      this.$refs.upload.clearFiles()
      this.dialogVisible = false
    }
  }
}
</script>
<style lang="less">
.recoveryDialogContent {
  width: 360px;
  margin: 0 auto;
}
</style>
